package com.aiyige.utils;

import com.aiyige.R;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.response.ErrorResponse;
import com.alibaba.fastjson.JSON;
import com.netease.nim.uikit.common.util.string.StringUtil;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Created by zhuyakun on 2018/2/11.
 */

public class ErrorUtil {
    public static ErrorResponse handleErrorResponse(Response<ResponseBody> response, boolean showToast) {
        ErrorResponse errorResposne = ErrorResponse.newBuilder().build();
        try {
            String json = RetrofitUtil.getResponseBodyAsString(response);
            errorResposne = new ErrorResponse(JSON.parseObject(json, ErrorResponse.class));
            if (showToast) {
                ToastX.show(errorResposne.getMessage());
            }
        } catch (Exception e) {
            ToastX.show(R.string.unknown_error);
        }
        return errorResposne;
    }


    public static ErrorResponse handleErrorResponse(Response<ResponseBody> response) {
        return handleErrorResponse(response, false);
    }

    public static String extractMessageFromErrorResponse(Response<ResponseBody> response) {
        if (response.code() >= ResponseCode.SERVER_ERROR) {
            return StringUtils.getString(R.string.server_error);
        } else {
            return handleErrorResponse(response, false).getMessage();
        }
    }

}
